package  {
	import flash.display.MovieClip;
	import flash.display.*;
	import flash.events.*;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.*;
	import SplitEvent;
	
	public class ImageSplitter extends MovieClip {
		
		private var _loader:Loader;
		private var _imgPath:String;
		private var _slices:int = 10; //One based
		private var _bitmapData:BitmapData;
		private var _stageHeight:Number;
		private var _imageParts:Array = []; //main object that is created. Array of image parts
		private var _bitmapPartWidth:Number;
		private var _position:int;
		
		public function ImageSplitter(imgPath:String, position:int, numberOfSlices:int) {
			//set variables to constructor argument values
			_imgPath = imgPath;
			_slices = numberOfSlices;
			_position = position
			
			//load image
			_loader = new Loader();
			_loader.load(new URLRequest(_imgPath));
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
		}
		
		//listen for load complete
		private function onComplete(e:Event):void {
			splitBitmap(e.target.loader.content.bitmapData);
		}
		
		private function splitBitmap(bitmapSource:BitmapData) {
			//define whole image size
			var bitmapWidth:Number = bitmapSource.width;
			var bitmapHeight:Number = bitmapSource.height;
			
			//define width of slice. Height comes from whole image size
			var _bitmapPartWidth:Number = bitmapWidth / _slices;
			
			//create bitmapData to whold whole image
			_bitmapData = new BitmapData(bitmapWidth, bitmapHeight);
			_bitmapData.draw(bitmapSource);
			
			//loop through total number of slices to create parts
			for (var i = 0; i < _slices; i++) {
				
				//create variable to whole bitmapData for the partial image
				var bitmapPartData:BitmapData = new BitmapData(_bitmapPartWidth, bitmapHeight);
				//fill that bitmapData with a selction of pixels copied from the whole image
				bitmapPartData.copyPixels(_bitmapData, new Rectangle(i * _bitmapPartWidth, 0, _bitmapPartWidth, bitmapHeight), new Point(0, 0));
				
				//instantiate the bitmap to hold the part and fill it
				var bitmapPart:Bitmap = new Bitmap(bitmapPartData);
				bitmapPart.smoothing = true;
				
				//copy that part to the array at the index of the current slice
				_imageParts[i] = bitmapPart;
			}
			dispatchEvent(new SplitEvent(SplitEvent.SPLIT_COMPLETE, _imageParts.length, _position));
		}
		
		public function get imageParts():Array {
			return _imageParts;
		}
		
		public function get numberSlices():int {
			return _slices;
		}
	}	
}